package com.athuahua.spzx.service.impl;

import com.athuahua.spzx.entity.vo.CategoryVo;
import com.athuahua.spzx.utils.CategoryMenuHelper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.Category;
import com.athuahua.spzx.service.CategoryService;
import com.athuahua.spzx.mapper.CategoryMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author huahua
* @description 针对表【category(商品分类)】的数据库操作Service实现
* @createDate 2024-08-09 16:23:34
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> selectOneCategory() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //limit 5 限制返回的结果条数，这里可以根据需要修改
        wrapper.eq(Category::getParentId, 0).last("limit 5");
        return categoryMapper.selectList(wrapper);
    }

    @Override
    public List<CategoryVo> findCategoryTree() {
        List<CategoryVo> allCategory = new ArrayList<>();
        //1.查询所有分类 返回list集合
        List<Category> categoryList = categoryMapper.selectList(
                new LambdaQueryWrapper<Category>()
                       .eq(Category::getStatus, 1)
                       .orderByAsc(Category::getStatus)
        );

        //2.遍历所有分类list集合，通过条件parentid=0得到所有一级分类
        categoryList.forEach(item ->{
                CategoryVo categoryVo = new CategoryVo();
                BeanUtils.copyProperties(item, categoryVo);
            allCategory.add(categoryVo);
        });
//
        //获得一二三级分类
        List<CategoryVo> oneCollect = allCategory.stream()
                .filter(item -> item.getParentId() == 0)
                .toList();
        oneCollect.forEach(one -> {
            //二级分类
            List<CategoryVo> twoCollect = allCategory.stream()
                    .filter(item -> item.getParentId().intValue() == one.getId())
                    .toList();
            one.setChildren(twoCollect);
            one.setHasChildren(!twoCollect.isEmpty());
            //三级分类
            twoCollect.forEach(two -> {
                List<CategoryVo> threeCollect = allCategory.stream()
                        .filter(item -> item.getParentId().intValue() == two.getId())
                        .toList();
                two.setChildren(threeCollect);
                two.setHasChildren(!threeCollect.isEmpty());
            });
        });

//        List<CategoryVo> oneCollect = CategoryMenuHelper.buildTree(allCategory);

        return oneCollect;
    }
}




